<template>
	<div :class="[disabled ? 'is_disabled' : 'is_valid']" class="x-edit-box">
		<div :id="'toolbar-' + uuid" class="toolbar" />
		<div ref="editor" :id="'editor-' + uuid" class="x-editor" />
	</div>
</template>

<script>
import objMixin from './objMixin'
import { v4 } from 'uuid'
import { createEditor, createToolbar } from '@wangeditor/editor'
export default {
	mixins: [objMixin],
	data() {
		return {
			// editor: null, // 富文本编辑器
			uuid: v4()
		}
	},
	props: {
		toolbarKeys: Array
	},
	watch: {
		value(val) {
			if (this.editor) {
				// 判断值不同才赋值，解决无法回车换行的问题
				const newHtml = this.editor.getHtml()
				if (newHtml !== val.html) {
					this.editor.setHtml(val.html)
				}
			}
		}
	},
	mounted() {
		const editorConfig = {
			placeholder: this.item.placeholder || '请输入内容',
			MENU_CONF: {
				uploadImage: {
					maxFileSize: 10 * 1024 * 1024,
					base64LimitSize: 500 * 1024 * 1024
				}
			},
			onChange: (editor) => {
				const newHtml = editor.getHtml()
				// if (newHtml !== this.value.html) {
				this.valueChange({
					html: newHtml
				})
				// }
				// 解决首字母没有输入法框的问题
				// if (newHtml === '') {
				// 	const textarea = this.$refs['editor'].querySelector(
				// 		'[contenteditable=true]'
				// 	)
				// 	if (!textarea) return
				// 	textarea.blur()
				// 	setTimeout(() => {
				// 		textarea.focus()
				// 	}, 100)
				// }
			}
		}

		const editor = createEditor({
			selector: '#editor-' + this.uuid,
			html: this.value.html,
			config: editorConfig,
			mode: 'default' // or 'simple'
		})
		const toolbarConfig = {}
		if (this.toolbarKeys) {
			toolbarConfig.toolbarKeys = this.toolbarKeys
		}

		const toolbar = createToolbar({
			editor,
			selector: '#toolbar-' + this.uuid,
			config: toolbarConfig,
			mode: 'default' // or 'simple'
		})
		this.editor = editor
	},
	methods: {}
}
</script>

<style lang="scss" scoped>
.x-edit-box {
	border: 1px solid #e0e0e0;
	position: relative;
	width: 100%;
	line-height: 15px;
	position: relative;
	&:hover .toolbar {
		pointer-events: painted;
		opacity: 1;
	}
}
.x-editor {
	min-height: 80px;
	max-height: 300px;
	overflow: auto;
	resize: vertical;
}
.toolbar {
	pointer-events: none;
	opacity: 0;
	transition: opacity 0.2s 0s;
	position: absolute;
	z-index: 9999;
	left: 0;
	right: 0;
	width: 100%;
	bottom: 99%;
	box-shadow: 0 0 10px 1px #e0e0e0;
}
::v-deep {
	.w-e-toolbar {
		overflow-x: visible;
	}
	.w-e-menu {
		z-index: auto !important;
	}
	.w-e-toolbar .w-e-droplist {
		z-index: 99999;
	}
}
</style>
